package com.kfm.kfmchat.conn;


import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.kfm.kfmchat.listener.ChatEventSourceListener;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import com.unfbx.chatgpt.sse.ConsoleEventSourceListener;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        sendStream();
    }

    public static void send() {
        //国内访问需要做代理，国外服务器不需要

        // 构建客户端
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey(Arrays.asList("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"))
                .okHttpClient(getOkHttpClient())
                //自己做了代理就传代理地址，没有可不不传
                .build();
        // 聊天模型：gpt-3.5
        Message message = Message.builder().role(Message.Role.USER).content("Java连接数据库").build();
        // 发送请求时候的请求体对象 model属性 messages 属性
        ChatCompletion chatCompletion = ChatCompletion.builder().temperature(0.7).messages(Arrays.asList(message)).build();
        // 封装了响应对象
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);
        chatCompletionResponse.getChoices().forEach(e -> {
            System.out.println(e.getMessage().getContent());
        });
    }

    public static void sendStream() {
        OpenAiStreamClient client = OpenAiStreamClient.builder()
                .apiKey(Arrays.asList("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"))
                .okHttpClient(getOkHttpClient())
                .build();
        // 构建一个向 控制台 输出内容的对象
        // ConsoleEventSourceListener eventSourceListener = new ConsoleEventSourceListener();
        // 聊天模型：gpt-3.5
        Message message = Message.builder().role(Message.Role.USER).content("Java连接数据库").build();
        // 发送请求时候的请求体对象 model属性 messages 属性
        ChatCompletion chatCompletion = ChatCompletion.builder().temperature(0.7).messages(Arrays.asList(message)).build();
        client.streamChatCompletion(chatCompletion, new ChatEventSourceListener());
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static OkHttpClient getOkHttpClient() {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //！！！！千万别再生产或者测试环境打开BODY级别日志！！！！
        //！！！生产或者测试环境建议设置为这三种级别：NONE,BASIC,HEADERS,！！！
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        return new OkHttpClient
                .Builder()
                .proxy(proxy)//自定义代理
                .addInterceptor(httpLoggingInterceptor)//自定义日志输出
                .addInterceptor(new OpenAiResponseInterceptor())//自定义返回值拦截
                .connectTimeout(10, TimeUnit.SECONDS)//自定义超时时间
                .writeTimeout(30, TimeUnit.SECONDS)//自定义超时时间
                .readTimeout(30, TimeUnit.SECONDS)//自定义超时时间
                .build();
    }
}
